package com.jy.common.config;


import cn.hutool.json.JSONUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Configuration
public class ALiYunOSSConfig {


    // accesskeyid
    public static final String ACCESSKEYID = "LTAI5tMbTia8NVH8iipLxLi3";
    // accesskeysecret
    public static final String ACCESSKEYSECRET = "PiyBb421VKz0gX2PTxbLJhtqETQSD8";
    // 地区
    public static final String REGIONID = "cn-hangzhou";
    // 角色Arn
    public static final String ROLEARN = "acs:ram::1750836364654613:role/fzg-jyapp";


    @Bean
    public IAcsClient client() {
        DefaultProfile profile = DefaultProfile.getProfile(REGIONID, ACCESSKEYID, ACCESSKEYSECRET);
        return new DefaultAcsClient(profile);
    }


    public Map<String, Object> getOSSStsToken(IAcsClient client) {
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(ROLEARN);
        // 设置一个自定义的角色会话名称，例如可以使用 UUID 来保证唯一性
        request.setRoleSessionName(UUID.randomUUID().toString());
        // 最大会话时间是 1 小时，单位是秒，你可以根据需要设置，但不能超过角色允许的最大值
        request.setDurationSeconds(43200L);


        AssumeRoleResponse response;
        try {
            response = client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            // 可以根据实际情况抛出更合适的异常或者返回错误信息
            return null;
        }


        Map<String, Object> map = new HashMap<>();
        map.put("securityToken", response.getCredentials().getSecurityToken());
        map.put("expiration", response.getCredentials().getExpiration());
        map.put("accessKeySecret", response.getCredentials().getAccessKeySecret());
        map.put("accessKeyId", response.getCredentials().getAccessKeyId());
        map.put("regionid", REGIONID);
        map.put("region", "oss-cn-hangzhou");
        map.put("bucket", "jyapp-fzg");
        System.out.println("临时凭证：");
        System.out.println(JSONUtil.toJsonStr(map));
        return map;
    }


}